<template>
  <div>
    <SearchBar :option="searchProps" @search="handleSearch"/>
    <div style="margin-left: auto; margin-bottom: 20px">
      <el-button plain type="primary" @click="() => materAddVisible = true">+ 添加电表</el-button>
    </div>
<!--    <div class="primary-section pv-12">-->
<!--      <el-space alignment="flex-end" :size="20">-->
<!--        <div class="fs-large ">本月数据</div>-->
<!--        <div>-->
<!--          <span class="fc-regular fs-small">总用电</span>-->
<!--          <span class="ml10 font-w">247.20度</span>-->
<!--        </div>-->
<!--        <div>-->
<!--          <span class="fc-regular fs-small">消费电量</span>-->
<!--          <span class="mfeat: 对接电表添加、列表接口l10 font-w">247.20度</span>-->
<!--        </div>-->
<!--        <div>-->
<!--          <span class="fc-regular fs-small">充值金额</span>-->
<!--          <span class="ml10 font-w">247.20度</span>-->
<!--        </div>-->
<!--        <div>-->
<!--          <el-button link type="primary" @click="handleHistoryRecord">历史记录 >></el-button>-->
<!--        </div>-->
<!--      </el-space>-->
<!--    </div>-->
    <el-table :data="list">
      <el-table-column label="名称" prop="name"></el-table-column>
      <el-table-column label="电表号" prop="number"></el-table-column>
      <el-table-column label="采集器	" prop="collectId"></el-table-column>
      <el-table-column label="更新时间" prop="onlineUpdateDate">
        <template #default="{ row }">
          <div class="flex-row-center">
            <span>{{ row.onlineUpdateDate }}</span>
            <el-icon @click="handleSync(row)" class="sync-icon" color="var(--el-color-primary)" size="20">
              <RefreshRight />
            </el-icon>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" min-width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="剩余金额" prop="remainAmount">
        <template #default="{ row }">
          {{ row.remainAmount }}元
        </template>
      </el-table-column>
      <el-table-column label="当前度数" prop="totalKwh">
        <template #default="{ row }">
          总：{{ row.totalKwh }} kwh
        </template>
      </el-table-column>
      <el-table-column label="关联房间 / 电表类型">
        <template #default="{ row }">
          <template v-if="row.room && row.room.name">
            <el-button link type="primary" @click="associationRoom(row)">
              {{ row.room.name }}
            </el-button>
          </template>
          <template v-else>
            <el-button link type="primary" @click="handleUnAssociation(row)">
              去关联
            </el-button>
          </template>
          / {{ '房间电表' }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <div class="flex-row-center">
            <el-button link type="primary" @click="handleMaterEdit(row)">编辑</el-button>
            <el-dropdown trigger="click" placement="bottom-start" @command="command => moreCommand(command, row)">
              <el-button link type="primary">更多</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="useRecord">用电记录</el-dropdown-item>
                  <el-dropdown-item command="recharge">充值</el-dropdown-item>
                  <el-dropdown-item 
                    v-if="row.status === '0' || row.status === '2'" 
                    command="reset"
                  >清零</el-dropdown-item>
                  <el-dropdown-item 
                    v-if="row.status === '1'" 
                    command="openAccount"
                  >开户</el-dropdown-item>
                  <el-dropdown-item command="remove">删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <OperationRecordDw ref="operationRef" />
    <SettingDl :visible="settingVisible" @ok="handleSettingOk" @cancel="handleSettingCancel" />
    <UseRecordDw ref="useRecordRef" :electricity-meter-id="currentRow?.electricityMeterId" :meter-name="currentRow?.name" />
    <MaterEdit :visible="materEditVisible" :row="selectRow" @ok="handleMaterEditOk" @cancel="handleMaterEditCancel" />
    <MaterAdd :visible="materAddVisible" :row="selectRow" @ok="handleMaterAddOk" @cancel="handleMaterAddCancel" />
    <AssociationRoomDrawer
      ref="associationRoomRef"
      :visible="accociation.visible"
      :deviceType="accociation.deviceType"
      :is-public="accociation.isPublic"
      :data="accociation.data"
      :total="accociation.total"
      v-model:page="accociation.pageNum"
      v-model:limit="accociation.pageSize"
      @pagination="handleGetAssociationList"
      @unbind="unbindRoom"
      @cancel="() => accociation.visible = false"
    />
    <UnAssociationRoomMeterDrawer
      v-model:visible="unAssociationRoomVisible"
      v-if="selectRow.electricityMeterId"
      :electricity-meter-id="selectRow.electricityMeterId"
      @bind-complete="bindComplete"
    />
    <HistoryRecord ref="historyRecordRef" />
    <RechargeDl
      v-if="rechargeVisible"
      v-model:visible="rechargeVisible"
      :electricity-meter-id="currentRow?.electricityMeterId"
      @ok="handleRechargeOk"
    />
    <OpenAccountDl
      v-if="openAccountVisible"
      v-model:visible="openAccountVisible"
      :electricity-meter-id="currentRow?.electricityMeterId"
      @ok="handleOpenAccountOk"
    />
  </div>
</template>
<script setup>
import SearchBar from '../component/searchBar.vue'
import { useRouter } from 'vue-router'
import OperationRecordDw from './operationRecordDw.vue'
import SettingDl from './settingDl.vue'
import UseRecordDw from './useRecordDw.vue'
import AssociationRoomDrawer from '../component/associationRoomDrawer.vue'
import MaterEdit from './materEdit.vue'
import MaterAdd from './materAdd.vue'
import HistoryRecord from './historyRecord.vue'
import RechargeDl from './rechargeDl.vue'
import OpenAccountDl from './openAccountDl.vue'
import { getList as getEleMeterList, onOffChange, sync, remove, reset, getBindRoomList, unBind } from '@/api/device/eleMeter'
import UnAssociationRoomMeterDrawer from '../component/unAssociationRoomMeterDrawer.vue'
import { RefreshRight } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance()
const router = useRouter()

const loading = ref(false)
const total = ref(0)
const list = ref([])
const queryParams = ref({})
const row = ref({})
const selectRow = ref({})
const settingVisible = ref(false)
const materEditVisible = ref(false)
const materAddVisible = ref(false)
const searchProps = ref({
  smartMeterType: {
    show: true,
    key: 'onOff',
    label: '电表状态',
    options: [
      { label: '开闸', value: '0' },
      { label: '关闸', value: '1' }
    ]
  },
  searchStr: {
    show: true,
    key: 'searchStr',
    placeholder: '请输入电表名称、电表号'
  }
})
const data = reactive({
  accociation: {
    deviceType: 1,
    isPublic: false,
    data: [],
    total: 0,
    pageNum: 1,
    pageSize: 20,
    visible: false
  }
})
const { accociation } = toRefs(data)

const pageNum = ref(1)
const pageSize = ref(10)
const rechargeVisible = ref(false)
const openAccountVisible = ref(false)
const unAssociationRoomVisible = ref(false)

function handleSearch(params) {
  pageNum.value = 1
  queryParams.value = { 
    ...queryParams.value, 
    ...params,
    pageNum: pageNum.value,
    pageSize: pageSize.value
  }
  getList()
}

function handleSizeChange(val) {
  pageSize.value = val
  getList()
}

function handleCurrentChange(val) {
  pageNum.value = val
  getList()
}

function getList() {
  loading.value = true
  const params = {
    ...queryParams.value,
    pageNum: pageNum.value,
    pageSize: pageSize.value
  }
  getEleMeterList(params).then(res => {
    if (res.code === 200) {
      list.value = res.rows
      total.value = res.total
    }
    loading.value = false
  })
}

const useRecordRef = ref()
const currentRow = ref(null)

// 获取状态文本
function getStatusText(status) {
  const statusMap = {
    '0': '初始化',
    '1': '已清零',
    '2': '已开户'
  }
  return statusMap[status] || '未知'
}

// 获取状态标签类型
function getStatusType(status) {
  const typeMap = {
    '0': 'info',
    '1': 'warning',
    '2': 'success'
  }
  return typeMap[status] || 'info'
}

/* 处理同步命令 */
function handleSync(row) {
  sync(row.electricityMeterId).then(res => {
    proxy.$message.success('同步成功, 数据会延迟更新, 请稍后查看!')
    setTimeout(() => {
      getList() // 刷新列表
    }, 2000)
  })
}

function moreCommand(command, row) {
  currentRow.value = row
  switch (command) {
    case 'useRecord':
      handleUseRecord()
      break
    case 'recharge':
      rechargeVisible.value = true
      break
    case 'reset':
      handleReset(row)
      break
    case 'openAccount':
      handleOpenAccount(row)
      break
    case 'oprRecord':
       handleHistoryRecord()
      break
    case 'remove':
      proxy.$modal.confirm('确定删除电表？').then(() => {
        return true
      }).then(() => {
        remove(row.electricityMeterId).then(res => {
          proxy.$modal.msgSuccess('删除成功');
          getList()
        })
      }).catch(() => {})
      break
    case 'switch':
      handleSwitch(row)
      break
    case 'setting':
      handleSetting(row)
      break
    default:
      break;
  }
}

/* 用电记录 */
function handleUseRecord() {
  if (currentRow.value?.electricityMeterId) {
    useRecordRef.value?.show()
  } else {
    proxy.$modal.msgError('电表ID不能为空')
  }
}

/* 历史记录 */
function handleHistoryRecord() {
  proxy.$refs['historyRecordRef'].show()
}

/* 电表开闸关闸 */
function handleOnOffChange(row) {
  const type = row.onOff === '1' ? 10 : 11
  const confirmText = row.onOff === '1' ? '确认关闸?' : '确认开闸?'
  proxy.$modal.confirm(confirmText)
      .then(res => {
        onOffChange(row.electricityMeterId, type).then(res => {
          proxy.$modal.msgSuccess(res.msg);
          getList()
        })
      })
      .catch(() => {
        row.onOff = row.off === '1' ? '0' : '1'
      })
}

/* 关联房间 */
function associationRoom(row) {
  selectRow.value = row
  accociation.value.isPublic = false
  handleGetAssociationList()
  accociation.value.visible = true
}

// 获取关联房间列表
function handleGetAssociationList() {
  loading.value = true
  const params = {
    pageNum: accociation.value.pageNum,
    pageSize: accociation.value.pageSize
  }
  
  // 调用获取关联房间列表接口
  getBindRoomList(selectRow.value.electricityMeterId, params).then(res => {
    if (res.code === 200) {
      accociation.value.data = res.data.map(item => {
        return {
          ...item,
          roomName: item.name
        }
      })
      accociation.value.total = res.data.length
    }
  }).finally(() => {
    loading.value = false
  })
}

/* 解绑房间 */
function unbindRoom(row) {
  proxy.$modal.confirm('确认要解绑该房间吗？').then(() => {
    unBind(selectRow.value.electricityMeterId).then(res => {
      if(res.code === 200) {
        proxy.$modal.msgSuccess('解绑成功')
        accociation.value.visible = false
        getList() // 刷新列表
      }
    })
  }).catch(() => {})
}

/* 切换预付费 */
function handleSwitch(row) {
  proxy.$modal.confirm('确认切换成预付费电表？')
    .then(res => {
      console.log('切换预付费');
    })
    .catch(() => {
      console.log('取消');
    })
}

/* 设置功率阈值 */
function handleSetting(row) {
  selectRow.value = row
  settingVisible.value = true
}
function handleSettingOk(value) {
  console.log(value);
  settingVisible.value = false
}
function handleSettingCancel() {
  settingVisible.value = false
  selectRow.value = {}
}

/* 编辑 */
function handleMaterEdit(row) {
  selectRow.value = row
  materEditVisible.value = true
}
function handleMaterEditOk(value) {
  console.log(value);
  materEditVisible.value = false
  getList()
}
function handleMaterEditCancel() {
  materEditVisible.value = false
}

/* 添加成功回调 */
function handleMaterAddOk() {
  materAddVisible.value = false
  getList() // 刷新列表
}

function handleMaterAddCancel() {
  materAddVisible.value = false
}

/* 充值成功回调 */
function handleRechargeOk() {
  getList() // 刷新列表
}

/* 电表清零 */
function handleReset(row) {
  proxy.$modal.confirm('确认要清零该电表吗？').then(() => {
    reset(row.electricityMeterId).then(res => {
      if(res.code === 200) {
        proxy.$modal.msgSuccess('清零成功')
        getList() // 刷新列表
      }
    })
  }).catch(() => {})
}

/* 电表开户 */
function handleOpenAccount(row) {
  currentRow.value = row
  openAccountVisible.value = true
}

/* 开户成功回调 */
function handleOpenAccountOk() {
  getList() // 刷新列表
}

/* 打开未关联房间抽屉 */
function handleUnAssociation(row) {
  selectRow.value = row
  unAssociationRoomVisible.value = true
}

/* 绑定完成回调 */
function bindComplete() {
  unAssociationRoomVisible.value = false
  getList() // 刷新列表
}

getList()
</script>

<style lang="scss" scoped>
.sync-icon {
  margin-left: 8px;
  cursor: pointer;
  transition: transform 0.3s ease;

  &:hover {
    transform: rotate(180deg);
  }
}
</style>
